package com.duff.download.okdownload.async;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * 并行异步任务调度器
 *
 * @author: duff
 * @date: 2019/3/31
 * @since: 1.0.0
 */
public class ParallelScheduler extends Scheduler {

    private static ThreadPoolImpl mThreadPool = new ThreadPoolImpl();

    /**
     * 执行一个异步任务
     *
     * @param task 后台任务
     */
    public static void execute(Runnable task) {
        if (task != null)
            mThreadPool.execute(task);
    }

    /**
     * @param backgroundTask 后台任务
     * @param frontTask      前台任务
     */
    public static void execute(final Runnable backgroundTask, final Runnable frontTask) {
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                if (backgroundTask != null)
                    backgroundTask.run();

                if (frontTask != null)
                    mHandler.post(frontTask);
            }
        });
    }

    /**
     * 执行一个 task {@link Task}
     *
     * @param task
     * @param <Params>
     * @param <Result>
     */
    public static <Params, Result> void execute(final Task<Params, Result> task) {
        mThreadPool.execute(new AsyncTask(task));
    }

    /**
     * @param task
     * @return Future<?>
     */
    public static Future<?> submit(Runnable task) {
        if (task != null)
            return mThreadPool.submit(task);
        return null;
    }

    /**
     * @param task
     * @param <T>
     * @return Future<T>
     */
    public static <T> Future<T> submit(Callable<T> task) {
        if (task != null)
            return mThreadPool.submit(task);
        return null;
    }

    /**
     * @param task
     * @param result
     * @param <T>    type
     * @return Future<T>
     */
    public static <T> Future<T> submit(Runnable task, T result) {
        if (task != null)
            return mThreadPool.submit(task, result);
        return null;
    }

}
